<template>
  <a-modal
    :title="editBoxState ? '编辑演职人员' : '新增演职人员'"
    :visible.sync="visible"
    @ok="handleSubmit"
    @cancel="handleCancel(false)"
  >
    <a-form :form="form">
      <a-form-item
        label="搜索"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="可根据姓名进行搜索，选择搜索的结果，可自动填充内容"
      >
        <a-select
          :value="value"
          showSearch
          :filterOption="false"
          @search="fetchUser"
          @change="handleChange"
          :notFoundContent="fetching ? undefined : null"
        >
          <a-spin v-if="fetching" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in data" :key="JSON.stringify(d)">{{
            d.name
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="姓名"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'name',
            {
              initialValue: initInfo.name,
              rules: [{ required: true, message: '请输入姓名！' }]
            }
          ]"
        >
        </a-input>
      </a-form-item>
      <a-form-item
        label="选择图片"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="建议图片宽高为：128px*170px，可去猫眼找图片上传"
      >
        <a-upload
          v-decorator="[
            'upload',
            {
              initialValue: initInfo.upload,
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
              rules: [{ required: true, message: '请上传演职人员头像' }]
            }
          ]"
          accept="image/*"
          listType="picture-card"
          name="file"
          :multiple="false"
          :showUploadList="false"
          :action="$api.upload"
          :data="postData"
          :beforeUpload="beforeUpload"
        >
          <img
            v-if="imageUrl"
            :src="$api.picPre + imageUrl"
            alt="avatar"
            style="width: 64px"
          />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传人员头像</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item
        label="职业"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          @change="changePosition"
          v-decorator="[
            'position',
            {
              initialValue: initInfo.position,
              rules: [{ required: true, message: '必选项' }]
            }
          ]"
        >
          <a-select-option value="导演">
            导演
          </a-select-option>
          <a-select-option value="演员">
            演员
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="角色"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="['role', { initialValue: initInfo.role, rules: role }]"
        />
      </a-form-item>
      <a-form-item
        label="排序"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'sort',
            {
              initialValue: initInfo.sort
            }
          ]"
        >
        </a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getToken } from "@/tool/qiniu";

export default {
  name: "addActor",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editBoxState: {
      type: Number, //编辑弹出框状态，0为新增框，1为编辑框
      default: 0
    },
    editInfo: {
      type: Object
    }
  },
  data() {
    this.fetchUser = this.$debounce(this.fetchUser, 800);
    this.handleSubmit = this.$debounce(this.handleSubmit, 800);
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      postData: {
        token: ""
      },
      initInfo: {
        upload: []
      },
      loading: false,
      imageUrl: null,
      role: [{ required: true, message: "请输入角色！" }],
      data: [],
      value: "",
      fetching: false
    };
  },
  methods: {
    fetchUser(value) {
      this.data = [];
      this.fetching = true;
      this.$ajax
        .get(this.$api.getActorList, {
          name: value
        })
        .then(res => {
          if (res.length === 0) {
            this.$notification.error({
              message: "该演职人员暂未搜索出相应结果，请添加"
            });
          }
          this.data = res;
          this.fetching = false;
        })
        .catch(err => {
          this.fetching = false;
          this.$notification.error({
            message: err
          });
        });
    },
    handleChange(value) {
      Object.assign(this, {
        value,
        fetching: false
      });
      let info = JSON.parse(value);
      this.form.setFieldsValue({
        name: info.name,
        position: info.position,
        upload: [
          {
            uid: "1",
            status: "done",
            url: this.$api.picPre + info.avatar,
            name: this.$api.picPre + info.avatar,
            response: {
              key: info.avatar
            }
          }
        ]
      });
      if (info.position === "导演") {
        this.role[0].required = false;
      } else {
        this.role[0].required = true;
      }
      this.imageUrl = info.avatar;
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = JSON.parse(JSON.stringify(values));
          if (values.upload) {
            obj.avatar = values.upload[0].response.key;
            delete obj.upload;
          }
          let api = null;
          if (this.editBoxState === 1) {
            api = this.$api.editProjectActorList;
            obj.id = this.initInfo.id;
            obj.type = 2;
          } else {
            api = this.$api.addProjectActorList;
            obj.type = 1;
          }
          obj.project_id = this.$route.params.id;
          this.$ajax
            .post(api, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.handleCancel(true);
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    changePosition(e) {
      if (e === "导演") {
        this.role[0].required = false;
      } else {
        this.role[0].required = true;
      }
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "actor/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 128;
        let height = 170;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为128px*170px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    handleCancel(isFresh) {
      this.form.resetFields();
      this.$emit("handleCancel", isFresh);
    }
  },
  watch: {
    editInfo: {
      handler: function(val) {
        this.value = "";
        this.imageUrl = "";
        this.initInfo = JSON.parse(JSON.stringify(val));
        if (this.initInfo.upload.length > 0) {
          if (this.initInfo.position === "导演") {
            this.role[0].required = false;
          } else {
            this.role[0].required = true;
          }
          this.imageUrl = this.initInfo.avatar;
        }
      },
      deep: true
    }
  }
};
</script>

<style scoped></style>
